package com.db.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Utils {
	private static final Log log = LogFactory.getLog(Utils.class);
	
	public static boolean strIsNotNull(String str) {
		if (str == null || str.trim().equals("")) {
			return false;
		}
		return true;
	}

	public static boolean strIsNull(String str) {
		return !strIsNotNull(str);
	}
	
	public static String stringifyException(Throwable e) {
		StringWriter stm = new StringWriter();
		PrintWriter wrt = new PrintWriter(stm);
		e.printStackTrace(wrt);
		wrt.close();
		return stm.toString();
	}
	
	public static byte[] objectToBytes(Object obj) {
		if(obj == null) {
			return null;
		}
		byte[] ret = null;
		ByteArrayOutputStream byteOut = null;
		ObjectOutputStream objOut = null;
		try {
			byteOut = new ByteArrayOutputStream();
			objOut = new ObjectOutputStream(byteOut);
			objOut.writeObject(obj);
			objOut.flush();
			if(byteOut != null) {
				ret = byteOut.toByteArray();
			}
		} catch (Exception e) {
			log.warn(stringifyException(e));
		} finally {
			if(objOut != null) {
				try {
					objOut.close();
				} catch (Exception e) {}
				objOut = null;
			}
			if(byteOut != null) {
				try {
					byteOut.close();
				} catch (Exception e) {}
				byteOut = null;
			}
		}
		return ret;
	}
	
	public static Object bytesToObject(byte[] byteArr) {
		if(byteArr == null || byteArr.length == 0) {
			log.warn("arr length is 0");
			return null;
		}
		Object obj = null;
		ByteArrayInputStream byteIn = null;
		ObjectInputStream objIn = null;
		try {
			byteIn = new ByteArrayInputStream(byteArr);
			objIn = new ObjectInputStream(byteIn);
			obj = objIn.readObject();
		} catch (Exception e) {
			log.warn(stringifyException(e));
		} finally {
			if(objIn != null) {
				try {
					objIn.close();
				} catch (Exception e) {}
				objIn = null;
			}
			if(byteIn != null) {
				try {
					byteIn.close();
				} catch (Exception e) {}
				byteIn = null;
			}
		}
		return obj;
	}
	
	public static String trim(String str) {
		if (str == null)
			return "";
		return str.trim();
	}
}
